<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class BF_Auth {

	public function __construct(){
		$this->ci =& get_instance();
		
		// Load BF Auth config
		$this->ci->load->config('bf_auth');
		$this->ci->load->library('Session');
		$this->_init();
	}
	
	function _init(){
		$this->deny_view = $this->ci->config->item('bf_login_url');
	}
	
	function _saltpassword($password){
		$params = array('iteration_count_log2' => 8, 'portable_hashes' => false);
		$this->ci->load->library('PasswordHash',$params);
		
		if(get_magic_quotes_gpc()) $password = stripslashes($password);
		
		$hash = $this->ci->passwordhash->HashPassword($password);
		
		return $hash;
	}
	
	public function create($email,$password){
		$this->ci->load->model('bf_auth/user_model', 'users');
		$this->ci->users->signup($email,$password);
	}
	
    public function login($username,$password) {
		$this->ci->load->model('bf_auth/user_model', 'users');
		
		$result = FALSE;
		
		if ($query = $this->ci->users->get_login($username) AND $query->num_rows() == 1) {
			$row = $query->row();
			if($row->password == $password):
				$this->_set_session($row);
				$result = TRUE;
			else:
				$result = FALSE;
			endif;
		}		
		return $result;
    }
	public function logout(){
		$this->ci->session->sess_destroy();
		redirect($this->ci->config->item('base_url'));
	}
	function _set_session($data){
		// Set session data array
		$user = array(						
			'BF_user_id'			=> $data->id,
			'BF_username'			=> $data->username,
			'BF_logged_in'			=> TRUE
		);
		
		$this->ci->session->set_userdata($user);
	}
	
	// Check if user is logged in
	public function is_logged_in(){
		return $this->ci->session->userdata('BF_logged_in');
	}
	public function check_logged_in(){
		$this->ci->load->helper('url');
		
		if (!$this->is_logged_in()){
			redirect(base_url().'auth/login', 'location');
		}
			
	}
}

/* End of file BF_Auth.php */